package com.vtb.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.vtb.base.VtbBaseServlet;
import com.vtb.entity.RrDetailInfo;
import com.vtb.entity.RrOauth;
import com.vtb.utils.RrTokenUtils;

/**
 * 人人用戶授权
 * 根据code获取access_token
 * 获取用户信息
 *
 * @author Chen Tao
 * @date 2012-7-1 下午06:52:44
 */
public class RrOauthServlet extends VtbBaseServlet {
	private static final Log log = LogFactory.getLog(RrOauthServlet.class);
	private static final long serialVersionUID = 1L;
	@SuppressWarnings("unused")
    public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		RrOauth rrOauth = null;
		RrDetailInfo rrDetailInfo = null;
		RrTokenUtils rrTokenUtils = new RrTokenUtils();
		try {
			//获取accessToken
			rrOauth = rrTokenUtils.getAccessToken(request, response);
			//关闭授权窗口 直接返回
			if (rrOauth.getUni().equals("code")) {
				response.sendRedirect("");
				return;
			}
			if (rrOauth == null) {
				throw new WtbException("获取AccessToken失败！");
			}
			//获取用户信息
			rrDetailInfo = rrTokenUtils.getUserInfo(rrOauth);
			if (rrDetailInfo.getUser() == null) {
				throw new WtbException("获取用户信息失败！");
			}
		} catch (Exception e) {
			log.error("人人用户授权失败：", e);
			response.sendRedirect("error?err_code=1002");
			return;
		}
		super.doSession(request, response);
		lastMap.put("rr", rrDetailInfo);
		session.setAttribute("lastMap", lastMap);
		session.setAttribute("status", null);
		response.sendRedirect("last");
	}
}
